"""

.. module:: <module>
.. moduleauthor:: @author: 

The purpose of this module is ... 
   
.. seealso:: modules :mod:`<module>`

*Constants*:
.. data:: constant_1
        
    constant_1 is used for ......
        
.. data:: constant_2
        
    constant_2 is used for ......
"""

# Imports
#
import logging
import os
import time
import unittest
from Queue import Queue
import urlparse

from datastore.database import DataStore
from datastore.resource import Resource
from runtime.rt import Runtime
from runtime.spaces import SpacesContext, Spaces
from spear.a2ptask import A2PTask
from runtime.boot import LoggingLevels

# Constants
#

# Classes
#

class A2PTaskTest(unittest.TestCase):
    """This class is a unit test for A2PTask. 

    *Usage examples*::

        example code

    *Common Arguments for Class methods*:
        <arguments>
    
    *Audience*:
        <audience>
    
    *Constants*:
        .. data:: constant_1
        
            constant_1 is used for ......
        
        .. data:: constant_2
        
            constant_2 is used for ......
    """

    def setUp(self):
        """This function initialises the unit test.
        """
        
        streamHandler = logging.StreamHandler()
        formatter = logging.Formatter("[%(asctime)s %(levelname)-8s %(threadName)s %(name)s %(module)s:%(lineno)d::%(funcName)s] %(message)s")
        streamHandler.setFormatter(formatter)
        logging.root.addHandler(streamHandler)
#        logging.root.setLevel(LoggingLevels.TRACE)
        logging.root.setLevel(logging.DEBUG)
        
        self.logger = logging.getLogger('eplanning.spear.a2ptasktest.A2PTaskTest')
        
        self.ds = DataStore(datastore_pathname="U:\\Test\\Distribution\\temp.datastore")
        self.spaces = Spaces()
        self.spaces_context = SpacesContext(self.spaces, Queue())
        
        # Initialise Runtime and Spaces. This results in the loading of spaces' 
        # namespace bindings.
        #
        runtime = Runtime()
        runtime.spaces_context = SpacesContext(self.spaces, Queue())
        
        config_file_rs_list = self.ds.find([(Resource.KEY_URI_DATASTORE_RESOURCE_TYPE, Resource.KEY_URI_PACKAGE_TYPE_CONFIGURATION)])
        site_file_rs_list = self.ds.find([(Resource.KEY_URI_DATASTORE_RESOURCE_TYPE, Resource.KEY_URI_PACKAGE_TYPE_SITE)])
        template_file_rs_list = self.ds.find([(Resource.KEY_URI_DATASTORE_RESOURCE_TYPE, Resource.KEY_URI_SERVICES_TYPE_TRANSFORM_TEMPLATE)])
        runtime.initialise_spaces(config_file_rs_list, site_file_rs_list, template_file_rs_list)
        
        self.logger.log(logging.DEBUG, "Starting A2PTask")
        
        task_uri = self.spaces_context.uri(Resource.BINDING_NS_NAME_TASK + ':')
        
        a2p_task = A2PTask(self.ds, self.spaces, task_uri.add("eplanning").add("spear").add("a2ptask"), Resource())
        a2p_task.start()
        time.sleep(1)
        
    def tearDown(self):
        """This function finalises the unit test.
        
        :param param_1: <class> or <type>
        :param param_2: <class> or <type>
        :rtype: <return type>
        """
        
        try:
            os.remove(self.temp_database_name)
        except:
            pass   

    def test_get_applicationlist(self):
        """This function tests a request for the Spear application list. This 
        assumes that all request and instruction configurations are loaded 
        into the datastore.
        """
        
        self.logger.log(logging.DEBUG, "")
        
        spear_uri = self.spaces_context.uri(A2PTask.BINDING_NS_NAME_SPEAR + ':')
        a2p_uri = self.spaces_context.uri(A2PTask.BINDING_NS_NAME_A2P + ':')
        
        self.logger.log(logging.DEBUG, "===================== Requesting sid002b")
        
        # create the request Resource - "Application List" (sid002b)
        #
        rs = Resource(namespaces=self.spaces.ns)
        rs.set_var(spear_uri.add("request").add("uri"), "req:applicationlist")
        
        new_uri = self.spaces_context.put(a2p_uri.add("userrequest"), rs)
#        self.logger.log(logging.DEBUG, "-------------------- Put Uri from A2PTask (%s)" % new_uri)
        rs = self.spaces_context.get_wait(new_uri.add("response"))
#        self.logger.log(logging.DEBUG, "-------------------- After get_wait() A2PTask (%s)" % rs.pretty_print())
        
        self.logger.log(logging.DEBUG, "===================== Requesting sid004")
        
        # create the request Resource - "Application Details" (sid004)
        # - this depends on "Application List"
        #
        args_dict = {}
        args_dict["spearReferenceNumber"] = "S005655E"
        args_dict["spearAppToken"] = "5727"
        
        rs = Resource(namespaces=self.spaces.ns)
        rs.set_var(spear_uri.add("request").add("uri"), "req:applicationdetails")
        rs.set_var("arguments_dict", args_dict)
        
        new_uri = self.spaces_context.put(a2p_uri.add("userrequest"), rs)
#        self.logger.log(logging.DEBUG, "-------------------- Put Uri from A2PTask (%s)" % new_uri)
        rs = self.spaces_context.get_wait(new_uri.add("response"))
#        self.logger.log(logging.DEBUG, "-------------------- After get_wait() A2PTask (%s)" % rs.pretty_print())
        
        # Dump the Spear application Resource.
        #
        spear_app_uri = spear_uri.add("app").add("S005655E")
        spear_app_rs = self.spaces_context.get(spear_app_uri)

        self.logger.log(logging.DEBUG, "--------------------- Resource for Spear Application (S005655E): (%s)" % (spear_app_rs.pretty_print()))
        
        self.logger.log(logging.DEBUG, "===================== Requesting documents")
    
        # let's get each document in the list just returned.
        #
        for document_dict in spear_app_rs.get_var("sid004_dict_list"):
            if (document_dict.has_key("document_url") is True):
                
                # Note: From the "Application Details" (sid004) page the documents
                #       clickthru as follows:
                #
                #       Applicant Contact:
                #       - Cultural Heritage Management Plan requirements
                #         > None
                #       - Copy of Title
                #         > sid005a
                #           > PDF
                #       - Plan of Elevations & Sections
                #         > sid005a
                #           > PDF
                #       - Site plan (existing)
                #         > sid005a
                #           > PDF
                #       - Site plan (proposed)
                #         > sid005a
                #           > PDF
                #       - Application for Planning Permit
                #         > sid005a
                #           > sid006a
                #       - Planning Property Report
                #         > services.land.vic.gov.au
                #
                #       Responsible Authority:
                #       - Application Acceptance / Rejection
                #         > sid005a
                #       - Other Document Type
                #         > sid005a
                #           > PDF
                #       - Responsible Authority Reference Number
                #         > sid072a
                #       - Modify Application Details
                #         > None
                #
                #       Referral Authorities:
                #
                #       Online Objectors:
                #
                #       VCAT:
                #
                
                if (document_dict.has_key("sid004_doctype")):
                    if (document_dict["sid004_doctype"] == "Cultural Heritage Management Plan requirements"):
                        self.logger.log(logging.DEBUG, "===================== Ignoring (%s)" % (document_dict["sid004_doctype"]))
                    
                    elif (document_dict["sid004_doctype"] == "Planning Property Report"):
                        # Non-Spear request.
                        #
                        self.logger.log(logging.DEBUG, "===================== Making non-Spear request (%s)" % (document_dict["sid004_doctype"]))
                        
                    elif (document_dict["sid004_doctype"] == "Responsible Authority Reference Number"):
                        # Request sid072a.
                        #
                        url = document_dict["document_url"]
                        url_parts = urlparse.urlparse(str(url))
                        
                        self.logger.log(logging.DEBUG, "===================== Requesting sid072a (%s)" % (document_dict["sid004_doctype"]))
                        
                        # create the request Resource - "Application Document" (sid005a)
                        # - this depends on "Application Details"
                        #
                        args_dict = {}
                        args_dict["documentUrlPath"] = url_parts.path
                        args_dict["documentUrlQuery"] = url_parts.query
                        args_dict["spearReferenceNumber"] = "S005655E"
                        
                        rs = Resource(namespaces=self.spaces.ns)
                        rs.set_var(spear_uri.add("request").add("uri"), "req:applicationdocument-responsibleauthorityreferencenumber")
                        rs.set_var("arguments_dict", args_dict)
                        
                        new_uri = self.spaces_context.put(a2p_uri.add("userrequest"), rs)
#                        self.logger.log(logging.DEBUG, "--------------------- Put Uri from A2PTask (%s)" % new_uri)
                        rs = self.spaces_context.get_wait(new_uri.add("response"))
                        
                    elif (document_dict["sid004_doctype"] == "Modify Application Details"):
                        self.logger.log(logging.DEBUG, "===================== Ignoring (%s)" % (document_dict["sid004_doctype"]))
                    
                    else:
                        # Request sid005a.
                        #
                        url = document_dict["document_url"]
                        url_parts = urlparse.urlparse(str(url))
                        
                        self.logger.log(logging.DEBUG, "===================== Requesting sid005a (%s)(%s)" % (document_dict["sid004_doctype"], url))
#                        self.logger.log(logging.DEBUG, "-------------------- url_parts path (%s), qs (%s)" % (url_parts.path, url_parts.query))
                        
                        # create the request Resource - "Application Document" (sid005a)
                        # - this depends on "Application Details"
                        #
                        args_dict = {}
                        args_dict["documentUrlPath"] = url_parts.path
                        args_dict["documentUrlQuery"] = url_parts.query
                        args_dict["spearReferenceNumber"] = "S005655E"
                        
                        rs = Resource(namespaces=self.spaces.ns)
                        rs.set_var(spear_uri.add("request").add("uri"), "req:applicationdocument")
                        rs.set_var("arguments_dict", args_dict)
                        
                        new_uri = self.spaces_context.put(a2p_uri.add("userrequest"), rs)
#                        self.logger.log(logging.DEBUG, "--------------------- Put Uri from A2PTask (%s)" % new_uri)
                        rs = self.spaces_context.get_wait(new_uri.add("response"))
#                        self.logger.log(logging.DEBUG, "--------------------- After get_wait() A2PTask (%s)" % rs.pretty_print())
                        
                        # Possibilities from this point are:
                        # - PDF
                        # - sid006a
                        # - None
                        #
                        
                        # Get the Spear application Resource again, because it has
                        # changed since we last looked at it.
                        #
                        spear_app_rs = self.spaces_context.get(spear_app_uri)
                        
                        if (spear_app_rs.has_var("sid005a_dict_dict")):
                            sid005a_dict_dict = spear_app_rs.get_var("sid005a_dict_dict")
                            self.logger.log(logging.DEBUG, "--------------------- sid005a_dict_dict (%s)" % sid005a_dict_dict)
                            
                            for current_document_doctype in sid005a_dict_dict:
                                self.logger.log(logging.DEBUG, "--------------------- current_document_doctype (%s)(%s)" % (current_document_doctype, sid005a_dict_dict[current_document_doctype]))
                                
                            if (sid005a_dict_dict.has_key(document_dict["sid004_doctype"]) is True):
                                sid005a_dict = sid005a_dict_dict[document_dict["sid004_doctype"]]
                                
                                if (sid005a_dict["sid005a_current_document_doctype"] == "Application for Planning Permit"):
                                    # Request sid006a.
                                    #
                                    url = sid005a_dict["document_url"]
                                    url_parts = urlparse.urlparse(str(url))
                                    
                                    args_dict = {}
                                    args_dict["documentUrlPath"] = url_parts.path
                                    args_dict["documentUrlQuery"] = url_parts.query
                                    args_dict["spearReferenceNumber"] = "S005655E"
                                    args_dict["documentType"] = sid005a_dict["sid005a_current_document_doctype"]
                                    
                                    self.logger.log(logging.DEBUG, "===================== Requesting sid006a (%s)(%s)" % (sid005a_dict["sid005a_current_document_doctype"], url))
                                    
                                    # create the request Resource - "Application Document Artefact" (sid006a)
                                    # - this depends on "Application Document" (sid005a)
                                    #
                                    rs = Resource(namespaces=self.spaces.ns)
                                    rs.set_var(spear_uri.add("request").add("uri"), "req:applicationdocument-applicationforplanningpermit")
                                    rs.set_var("arguments_dict", args_dict)
                                    
                                    new_uri = self.spaces_context.put(a2p_uri.add("userrequest"), rs)
    #                                self.logger.log(logging.DEBUG, "--------------------- Put Uri from A2PTask (%s)" % new_uri)
                                    rs = self.spaces_context.get_wait(new_uri.add("response"))
    #                                self.logger.log(logging.DEBUG, "--------------------- After get_wait() A2PTask (%s)" % rs.pretty_print())
                                
                                elif (sid005a_dict["sid005a_current_document_doctype"] == "Application Acceptance / Rejection"):
                                    self.logger.log(logging.DEBUG, "===================== Have just processed (%s). No further pages." % (sid005a_dict["sid005a_current_document_doctype"]))
                                
                                else:
                                    # Request PDF.
                                    #
                                    url = sid005a_dict["document_url"]
                                    url_parts = urlparse.urlparse(str(url))
                                    
                                    args_dict = {}
                                    args_dict["documentUrlPath"] = url_parts.path
                                    args_dict["documentUrlQuery"] = url_parts.query
                                    args_dict["spearReferenceNumber"] = "S005655E"
                                    args_dict["documentType"] = sid005a_dict["sid005a_current_document_doctype"]
                                    
                                    self.logger.log(logging.DEBUG, "===================== Requesting PDF (%s)(%s)" % (sid005a_dict["sid005a_current_document_doctype"], url))
                                    
                                    # create the request Resource - "Application Document (PDF)"
                                    # - this depends on "Application Document" (sid005a)
                                    #
                                    rs = Resource(namespaces=self.spaces.ns)
                                    rs.set_var(spear_uri.add("request").add("uri"), "req:applicationdocument-pdf")
                                    rs.set_var("arguments_dict", args_dict)
                                    
                                    new_uri = self.spaces_context.put(a2p_uri.add("userrequest"), rs)
    #                                self.logger.log(logging.DEBUG, "--------------------- Put Uri from A2PTask (%s)" % new_uri)
                                    rs = self.spaces_context.get_wait(new_uri.add("response"))
    #                                self.logger.log(logging.DEBUG, "--------------------- After get_wait() A2PTask (%s)" % rs.pretty_print())
                                
            
#        spaces_context.delete(uri_tasks.eplanning.spear.a2ptask)
#        self.assertEqual(rs.error, 'You must specify a keyword.')
        
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()